﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SO_DataFetcher.PubFunctions
{
    public class PubCsv
    {
        public static void ExportCsv(string fileName,DataTable dataTable)
        {
            StreamWriter sw = new StreamWriter(fileName, true, System.Text.Encoding.GetEncoding("GB2312"));

            sw.AutoFlush = true;
            string title = string.Empty;

            int i = 0;
            foreach (DataColumn column in dataTable.Columns)
            {
                if (i == 0)
                {
                    title = column.Caption;
                    i++;
                }
                else
                {
                    title = title + "," + column.Caption;
                }
            }

            sw.WriteLine(title);

            string[] columnNames = title.Split(',');

            foreach (DataRow dataRow in dataTable.Rows)
            {
                i = 0;
                string line = string.Empty;
                foreach (string name in columnNames)
                {
                    if (i == 0)
                    {
                        line = dataRow[name].ToString();
                        i++;
                    }
                    else
                        line = line + "," + dataRow[name].ToString();
                }

                sw.WriteLine(line);
            }

            sw.Flush();
            sw.Close();
        }
    }
}
